package com.cbtx.module_sp.ui.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.RelativeLayout;

import com.cbtx.module.base.ui.BaseActivity;
import com.cbtx.module_sp.R;

import org.jetbrains.annotations.NotNull;

import java.util.Timer;
import java.util.TimerTask;


/**
 * 视频播放界面
 * <p/>
 * Created by huangjun on 2015/4/11.
 */
public class WatchVideoActivity extends BaseActivity implements Callback {
    public static final String INTENT_EXTRA_DATA = "EXTRA_DATA";
    public static final String INTENT_EXTRA_MENU = "EXTRA_MENU";


    public static final int REQUEST_CODE_FORWARD_PERSON = 0x01;
    public static final int REQUEST_CODE_FORWARD_TEAM = 0x02;

    // player

    private MediaPlayer mediaPlayer;

    // context

    private Handler handlerTimes = new Handler();

//    private ActionBar actionBar;






    private SurfaceView surfaceView;

    private SurfaceHolder surfaceHolder;





    private boolean isSurfaceCreated = false;

    protected String videoFilePath;

    private float lastPercent;

    private int playState = PLAY_STATE_STOP;

    private final static int PLAY_STATE_PLAYING = 1;

    private final static int PLAY_STATE_STOP = 2;

    private final static int PLAY_STATE_PAUSE = 3;

    // download control
    private boolean downloading;
    //    private ImageView downloadBtn;



    private Timer mTimer;
    private TimerTask mTimerTask;
    private boolean isChanging = false;//互斥变量，防止定时器与SeekBar拖动时进度冲突

    int videoWidth = 0;
    int videoHeight = 0;




    @Override
    public int getLayoutId() {
        return R.layout.sp_fragment_adv_video;
    }

    @Override
    public void initView(@org.jetbrains.annotations.Nullable Bundle savedInstanceState) {



        findViews();




    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    public void onResume() {
        super.onResume();
        mediaPlayer = new MediaPlayer();

        playVideo();
    }

    @Override
    public void onPause() {
        super.onPause();

        stopMediaPlayer();
    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    private void findViews() {


        surfaceView = findViewById(R.id.mSurfaceView);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceHolder.addCallback(this);


    }


    private void initVideoSize() {
        if (mediaPlayer == null) {
            return;
        }
        // 视频宽高
        videoWidth = mediaPlayer.getVideoWidth();
        videoHeight = mediaPlayer.getVideoHeight();

        if (videoWidth <= 0 || videoHeight <= 0) {
            return;
        }

        // 屏幕宽高
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;

        int videoRatio = videoWidth / videoHeight;
        int screenRatio = screenWidth / screenHeight;

        if (screenRatio > videoRatio) {
            int newHeight = screenHeight;
            int newWidth = screenHeight * videoWidth / videoHeight;
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                    newWidth, newHeight);
            int margin = (screenWidth - newWidth) / 2;
            layoutParams.setMargins(margin, 0, margin, 0);
            surfaceView.setLayoutParams(layoutParams);
        } else {
            int newWidth = screenWidth;
            int newHeight = screenWidth * videoHeight / videoWidth;
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                    newWidth, newHeight);
            int margin = (screenHeight - newHeight) / 2;
            layoutParams.setMargins(0, margin, 0, margin);
            surfaceView.setLayoutParams(layoutParams);
        }
    }

    /**
     * ****************************** MediaPlayer Start ********************************
     */
    private void stopMediaPlayer() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    /**
     * 处理视频播放时间
     */
    private Runnable timeRunnable = new Runnable() {
        public void run() {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                playState = PLAY_STATE_PLAYING;


            }
        }
    };

    protected void pauseVideo() {

        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            handlerTimes.removeCallbacks(timeRunnable);
            playState = PLAY_STATE_PAUSE;
        }
    }

    protected void resumeVideo() {

        if (mediaPlayer != null) {
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                playState = PLAY_STATE_PLAYING;
                handlerTimes.postDelayed(timeRunnable, 100);
            }
        }
    }

    protected void playVideo() {





        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            } else {
                if (isSurfaceCreated) {
                    mediaPlayer.setDisplay(surfaceHolder);
                } else {

                    return;
                }
            }
            mediaPlayer.reset();
            try {
                mediaPlayer.setDataSource(videoFilePath);
            } catch (Exception e) {

                e.printStackTrace();
                return;
            }

            setMediaPlayerListener();
            mediaPlayer.prepareAsync();
//            actionBar.hide();
        }
    }

    private void setMediaPlayerListener() {
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {


                playState = PLAY_STATE_STOP;
                //为了避免 例如 4.5秒的视频播放结束后，显示不一致


                handlerTimes.removeCallbacks(timeRunnable);


            }
        });

        mediaPlayer.setOnErrorListener(new OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    String type = "video/3gp";
                    Uri name = Uri.parse("file://" + videoFilePath);
                    intent.setDataAndType(name, type);
                    startActivity(intent);
                    finish();
                } catch (Exception e) {

                }
                return true;
            }
        });

        mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp)// 缓冲完毕
            {
                mediaPlayer.start();// 播放视频
                initVideoSize();//根据视频宽高，调整视频显示
                // if (position > 0) {
                // mediaPlayer.seekTo(position);
                // mediaPlayer.start();
                // }
                handlerTimes.postDelayed(timeRunnable, 100);
            }
        });
    }














    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
//        ToastHelper.showToast(this, R.string.surface_created);
        if (!isSurfaceCreated) {
            isSurfaceCreated = true;

        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isSurfaceCreated = false;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        initVideoSize();// 屏幕旋转后，改变视频显示布局
    }







    @Override
    public void onMyViewClick(@NotNull View view) {

    }

    @Override
    public void getData() {

    }


}


